#pragma once
#include <iostream>
#include "ERRNO.hpp"
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string>
#include <cstdlib>
#include <functional>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <cstring>
#include "protocol.hpp"
using namespace std;



void Handler(const Request &rq, Response &res)
{
    res._exitcode = NORMAL ;
    switch (rq._op)
    {
    case '+':
    {
        res._result = rq._x+rq._y;
        break;
    }
    case '-':
    {
        res._result = rq._x - rq._y;
        break;
    }
    case '*':
    {
        res._result = rq._x*rq._y;
        break;
    }
    case '/':
    {
        if(rq._y==0)
        {
            res._exitcode = DIV_ZERO;
        }
        else
        res._result = rq._x/rq._y;
        break;
    }
    case '%':
    {
        if(rq._y==0)
        {
            res._exitcode = MOD_ZERO;
        }
        else
        res._result = rq._x%rq._y;
        break;
    }
    default:
    {
        res._exitcode = UNKNOWN_OP;
        break;
    }
    }
}
void GET(int sock, uint16_t clientport, string clientip) // 主逻辑
{
    while (1)
    {
        string inbuffer; // 用来保存所有从内核缓冲区read的数据，提取完一个完整报文之后就删除该报文，剩下的还是要保留
        // 1读取一个完整的请求
        string request;
        ReadOneText(sock, request, inbuffer);
        // cout<<"RECV:"<<request<<endl;
        // 2反序列化获得一个结构化的请求？
        Request rq;
        rq.Deserialize(request);

        // 3 业务逻辑
        Response res;
        Handler(rq, res);

        // 4相应序列化
        string outbuffer;
        outbuffer = res.Serialize();
        // cout<<"outbuffer:"<<outbuffer<<endl;
        outbuffer = EnHeader(outbuffer);
        // cout<<"Send out : "<<outbuffer<<endl;
        // 5返回相应
        int n = write(sock, outbuffer.c_str(), outbuffer.size());
        if (n <= 0)
            exit(0);
        (void)n;
    }
}
